package jal4eclipse.ui.editors;

import jal4eclipse.builder.JALBuilder;
import jal4eclipse.jal.JALCompileResult;
import jal4eclipse.ui.console.JALConsole;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.ui.ide.ResourceUtil;

public class JALEditorKeyEvent implements KeyListener {
	private JALEditor editor;

	public JALEditorKeyEvent(JALEditor editor) {
		super();
		this.editor = editor;
		
	}

	public void keyReleased(KeyEvent evt) {
	}

	public void keyPressed(KeyEvent evt) {
		 
		/*
		 * Manually compile file using F9 key
		 * works even if the project as no JAL nature...
		 */
		if (SWT.F9 == evt.keyCode) {
			IResource resource = ResourceUtil.getResource(editor.getEditorInput());
			if ("jal".equals(resource.getFileExtension())) {
			    editor.doSave(null);
				JALCompileResult result = JALBuilder.compileResource(resource);
				JALBuilder.updateMarkers(resource,result);
				JALConsole.write(result.getCommandLine());
				JALConsole.write(result.getResult());
				try {
					ResourcesPlugin.getWorkspace().getRoot().refreshLocal(
							IResource.DEPTH_INFINITE, null);
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
		} else if (' ' == evt.character) {
			/* Auto complete structure */
			JALCompletStructureProcessor.codeAssist((StyledText) evt.getSource());
		}
	}

}
